# -*- coding:utf-8 -*-

from importlib import import_module
import threading
import types


class Container(object):
    container_bind = {
        "DB": {"instance": "DB", "module": ".mysql.db", "package": __package__},
        "Connection": {
            "instance": "Connection",
            "module": ".mysql.connection",
            "package": __package__,
            "handle_end": "close",
        },
    }
    # 全局实例
    local = threading.local()

    def __init__(self) -> types.NoneType:
        if not hasattr(self.local, 'container_instance'):
            self.local.container_instance = {}
        pass

    def get_instance(self, name: str):
        if name not in self.local.container_instance:
            obj_ = self.container_bind.get(name)
            if not obj_:
                return None
            module_name = obj_.get("module")
            module = import_module(module_name, obj_.get("package"))
            instance = getattr(module, obj_.get("instance"))
            print('get_instance',instance)
            self.local.container_instance[name] = instance()
        return self.local.container_instance[name]

    @classmethod
    def instance(cls, name: str):
        instance = cls().get_instance(name)
        if not instance:
            raise Exception(f"{name} instance error")
        return instance

    @classmethod
    def handle_end(cls):
        for name in cls.container_bind:
            obj = cls.container_bind[name]
            method_name = obj.get("handle_end", None)
            print(f"name:{name}, method:{method_name}")
            if method_name is None:
                continue
            instance = cls.instance(name)
            method = getattr(instance, method_name, None)
            if not isinstance(method, types.MethodType):
                continue
            method()
